<?php
class CommonAction extends Action {
		function _initialize() {
				 ini_alter("session.gc_maxlifetime", 28800);//会话时间延长到8小时
				if(!file_exists(DATA_PATH.'~config.php')) {
						$config = M("Configure");
						$list = $config->getField('var_name,value');
						// 所有配置参数统一为大写
						$tmp = array();
						foreach($list as $key=>$value) {
								if(0 === strpos($value,'array(')) {
										$str = '$tmp[$key]='.$value.';';
										eval($str);
								}else {
										$tmp[$key] = $value;
								}
						}
						$content =   "<?php\nreturn ".var_export(array_change_key_case($tmp,CASE_UPPER),true).";\n?>";
						if(!file_put_contents(DATA_PATH.'~config.php',$content)) {
								$this->error('配置缓存失败！');
						}
				}
				C(include_once DATA_PATH.'~config.php');
				// 用户权限检查
				if (C ( 'USER_AUTH_ON' ) && !in_array(MODULE_NAME,explode(',',C('NOT_AUTH_MODULE')))) {
						import ( '@.ORG.RBAC' );
						if (! RBAC::AccessDecision ()) {
								//检查认证识别号
								if (! $_SESSION [C ( 'USER_AUTH_KEY' )]) {
										//跳转到认证网关
										redirect ( PHP_FILE . C ( 'USER_AUTH_GATEWAY' ) );
								}
								// 没有权限 抛出错误
								if (C ( 'RBAC_ERROR_PAGE' )) {
										// 定义权限错误页面
										redirect ( C ( 'RBAC_ERROR_PAGE' ) );
								} else {
										if (C ( 'GUEST_AUTH_ON' )) {
												$this->assign ( 'jumpUrl', PHP_FILE . C ( 'USER_AUTH_GATEWAY' ) );
										}
										// 提示错误信息
										$this->error ( L ( '_VALID_ACCESS_' ) );
								}
						}
				}
		}
		public function index() {
				//列表过滤器，生成查询Map对象
				$map = $this->_search ();
				if (method_exists ( $this, '_filter' )) {
						$this->_filter ( $map );
				}
				$name=$this->getActionName();
				$model = D ($name);
				if (! empty ( $model )) {
						$this->_list ( $model, $map );
				}
				$this->display ();
				return;
		}
		/**
		 +----------------------------------------------------------
		 * 取得操作成功后要返回的URL地址
		 * 默认返回当前模块的默认操作
		 * 可以在action控制器中重载
		 +----------------------------------------------------------
		 * @access public
		 +----------------------------------------------------------
		 * @return string
		 +----------------------------------------------------------
		 * @throws ThinkExecption
		 +----------------------------------------------------------
		 */
		function getReturnUrl() {
				return __URL__ . '?' . C ( 'VAR_MODULE' ) . '=' . MODULE_NAME . '&' . C ( 'VAR_ACTION' ) . '=' . C ( 'DEFAULT_ACTION' );
		}

		/**
		 +----------------------------------------------------------
		 * 根据表单生成查询条件
		 * 进行列表过滤
		 +----------------------------------------------------------
		 * @access protected
		 +----------------------------------------------------------
		 * @param string $name 数据对象名称
		 +----------------------------------------------------------
		 * @return HashMap
		 +----------------------------------------------------------
		 * @throws ThinkExecption
		 +----------------------------------------------------------
		 */
		protected function _search($name = '') {
				//生成查询条件
				if (empty ( $name )) {
						$name = $this->getActionName();
				}
				$name=$this->getActionName();
				$model = D ( $name );
				$map = array ();
				foreach ( $model->getDbFields () as $key => $val ) {
						if (isset ( $_REQUEST [$val] ) && $_REQUEST [$val] != '') {
								$map [$val] = $_REQUEST [$val];
						}
				}
				return $map;

		}

		/**
		 +----------------------------------------------------------
		 * 根据表单生成查询条件
		 * 进行列表过滤
		 +----------------------------------------------------------
		 * @access protected
		 +----------------------------------------------------------
		 * @param Model $model 数据对象
		 * @param HashMap $map 过滤条件
		 * @param string $sortBy 排序
		 * @param boolean $asc 是否正序
		 +----------------------------------------------------------
		 * @return void
		 +----------------------------------------------------------
		 * @throws ThinkExecption
		 +----------------------------------------------------------
		 */
		protected function _list($model, $map, $sortBy = '', $asc = false) {
				//排序字段 默认为主键名
				if (isset ( $_REQUEST ['_order'] )) {
						$order = $_REQUEST ['_order'];
				} else {
						$order = ! empty ( $sortBy ) ? $sortBy : $model->getPk ();
				}
				//排序方式默认按照倒序排列
				//接受 sost参数 0 表示倒序 非0都 表示正序
				if (isset ( $_REQUEST ['_sort'] )) {
						$sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
				} else {
						$sort = $asc ? 'asc' : 'desc';
				}
				//取得满足条件的记录数
				$count = $model->where ( $map )->count ( 'id' );
				if ($count > 0) {
						import ( "@.ORG.Page" );
						//创建分页对象
						if (! empty ( $_REQUEST ['listRows'] )) {
								$listRows = $_REQUEST ['listRows'];
						} else {
								$listRows = '';
						}
						$p = new Page ( $count, $listRows );
						//分页查询数据

						$voList = $model->where($map)->order( "`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->findAll ( );
						//echo $model->getlastsql();
						//分页跳转的时候保证查询条件
						foreach ( $map as $key => $val ) {
								if (! is_array ( $val )) {
										if( C('URL_MODEL') == 3 ) {
												$p->parameter .= "&$key=" . urlencode ( $val ) . "&";//url_modl=3,then add &
										}else {
												$p->parameter .= "$key=" . urlencode ( $val ) . "&";//url_modl !=3
										}
								}
						}
			if ($_REQUEST['keywords']!='') {
				$p->parameter .= 'keywords='.urlencode($_REQUEST['keywords']).'&';
			}
						//分页显示
						$page = $p->show ();
						//列表排序显示
						$sortImg = $sort; //排序图标
						$sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
						$sort = $sort == 'desc' ? 1 : 0; //排序方式
						//模板赋值显示
						$this->assign ( 'list', $voList );
						$this->assign ( 'sort', $sort );
						$this->assign ( 'order', $order );
						$this->assign ( 'sortImg', $sortImg );
						$this->assign ( 'sortType', $sortAlt );
						$this->assign ( "page", $page );
				}
				Cookie::set ( '_currentUrl_', __SELF__ );
				return;
		}

		function insert() {
				$jumpUrl = $_REQUEST['jumpUrl'];
				//B('FilterString');
				$name=$this->getActionName();
				$model = D ($name);
				if (false === $model->create ()) {
						$this->error ( $model->getError () );
				}
				//保存当前数据对象
				$list=$model->add ();
				if ($list!==false) { //保存成功
						if(empty($jumpUrl))
								$jumpUrl = Cookie::get ( '_currentUrl_' );
						$this->assign ( 'jumpUrl', $jumpUrl );
						$this->success ('新增成功!');
				} else {
						//失败提示
						$this->error ('新增失败!');
				}
		}

		public function add() {
				$this->display ();
		}

		function read() {
				$this->edit ();
		}

		function edit() {
				$name=$this->getActionName();
				$model = M ( $name );
				$id = $_REQUEST [$model->getPk ()];
				$vo = $model->getById ( $id );
				$this->assign ( 'vo', $vo );
				$this->display ();
		}

		function update() {
				 $jumpUrl = $_REQUEST['jumpUrl'];
				//B('FilterString');
				$name=$this->getActionName();
				$model = D ( $name );
				if (false === $model->create ()) {
						$this->error ( $model->getError () );
				}
				// 更新数据
				$list=$model->save ();
				if (false !== $list) {
						if(empty($jumpUrl))
								$jumpUrl = Cookie::get ( '_currentUrl_' );
						$this->assign ( 'jumpUrl', $jumpUrl );
						$this->success ('编辑成功!');
				} else {
						//错误提示
						$this->error ('编辑失败!');
				}
		}
		/**
		 +----------------------------------------------------------
		 * 默认删除操作
		 +----------------------------------------------------------
		 * @access public
		 +----------------------------------------------------------
		 * @return string
		 +----------------------------------------------------------
		 * @throws ThinkExecption
		 +----------------------------------------------------------
		 */
		public function delete() {
				//删除指定记录
				$name=$this->getActionName();
				$model = M ($name);
				if (! empty ( $model )) {
						$pk = $model->getPk ();
						$id = $_REQUEST [$pk];
						if (isset ( $id )) {
								$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
								$list=$model->where ( $condition )->setField ( 'status', - 1 );
								if ($list!==false) {
										$this->success ('删除成功！' );
								} else {
										$this->error ('删除失败！');
								}
						} else {
								$this->error ( '非法操作' );
						}
				}
		}
		public function foreverdelete() {
				$jumpUrl = $_REQUEST['jumpUrl'];
				//删除指定记录
				$name=$this->getActionName();
				$model = D ($name);
				if (! empty ( $model )) {
						$pk = $model->getPk ();
						$id = $_REQUEST [$pk];
						if (isset ( $id )) {
								$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
								if (false !== $model->where ( $condition )->delete ()) {
										//echo $model->getlastsql();
										if(empty($jumpUrl))
												$jumpUrl = Cookie::get ( '_currentUrl_' );
										$this->assign ( 'jumpUrl', $jumpUrl );
										$this->success ('删除成功！');
								} else {
										$this->error ('删除失败！');
								}
						} else {
								$this->error ( '非法操作' );
						}
				}
				$this->forward ();
		}

		public function clear() {
				//删除指定记录
				$name=$this->getActionName();
				$model = D ($name);
				if (! empty ( $model )) {
						if (false !== $model->where ( 'status=1' )->delete ()) {
								$this->assign ( "jumpUrl", $this->getReturnUrl () );
								$this->success ( L ( '_DELETE_SUCCESS_' ) );
						} else {
								$this->error ( L ( '_DELETE_FAIL_' ) );
						}
				}
				$this->forward ();
		}
		/**
		 +----------------------------------------------------------
		 * 默认禁用操作
		 *
		 +----------------------------------------------------------
		 * @access public
		 +----------------------------------------------------------
		 * @return string
		 +----------------------------------------------------------
		 * @throws FcsException
		 +----------------------------------------------------------
		 */
		public function forbid() {
				$name=$this->getActionName();
				$model = D ($name);
				$pk = $model->getPk ();
				$id = $_REQUEST [$pk];
				$condition = array ($pk => array ('in', $id ) );
				$list=$model->forbid ( $condition );
				if ($list!==false) {
						//模式为3时，this->getReturnUrl()会返回错误，故不应在resume,forbid下使用。
						//$this->assign ( "jumpUrl", $this->getReturnUrl () );
						$this->success ( '状态禁用成功' );
				} else {
						$this->error  (  '状态禁用失败！' );
				}
		}
		public function checkPass() {
				$name=$this->getActionName();
				$model = D ($name);
				$pk = $model->getPk ();
				$id = $_GET [$pk];
				$condition = array ($pk => array ('in', $id ) );
				if (false !== $model->checkPass( $condition )) {
						$this->assign ( "jumpUrl", $this->getReturnUrl () );
						$this->success ( '状态批准成功！' );
				} else {
						$this->error  (  '状态批准失败！' );
				}
		}

		//okhome相关操作记录的审核通过
		public function homeCheckPass() {
				$name=$this->getActionName();
				$model = D ($name);
				$pk = $model->getPk ();
				$id = $_GET [$pk];
				$condition = array ($pk => array ('in', $id ) );
				if (false !== $model->checkPass( $condition, 'check_status' )) {
						//$this->assign ( "jumpUrl", $this->getReturnUrl () );
						$this->success ( '审核通过！' );
				} else {
						$this->error  (  '审核失败！' );
				}
		}

		public function recycle() {
				$name=$this->getActionName();
				$model = D ($name);
				$pk = $model->getPk ();
				$id = $_GET [$pk];
				$condition = array ($pk => array ('in', $id ) );
				if (false !== $model->recycle ( $condition )) {

						$this->assign ( "jumpUrl", $this->getReturnUrl () );
						$this->success ( '状态还原成功！' );

				} else {
						$this->error   (  '状态还原失败！' );
				}
		}

		public function recycleBin() {
				$map = $this->_search ();
				$map ['status'] = - 1;
				$name=$this->getActionName();
				$model = D ($name);
				if (! empty ( $model )) {
						$this->_list ( $model, $map );
				}
				$this->display ();
		}

		/**
		 +----------------------------------------------------------
		 * 默认恢复操作
		 *
		 +----------------------------------------------------------
		 * @access public
		 +----------------------------------------------------------
		 * @return string
		 +----------------------------------------------------------
		 * @throws FcsException
		 +----------------------------------------------------------
		 */
		function resume() {
				//恢复指定记录
				$name=$this->getActionName();
				$model = D ($name);
				$pk = $model->getPk ();
				$id = $_GET [$pk];
				$condition = array ($pk => array ('in', $id ) );
				if (false !== $model->resume ( $condition )) {
						//$this->assign ( "jumpUrl", $this->getReturnUrl () );
						$this->success ( '状态恢复成功！' );
				} else {
						$this->error ( '状态恢复失败！' );
				}
		}


		function saveSort() {
				$seqNoList = $_POST ['seqNoList'];
				if (! empty ( $seqNoList )) {
						//更新数据对象
						$name=$this->getActionName();
						$model = D ($name);
						$col = explode ( ',', $seqNoList );
						//启动事务
						$model->startTrans ();
						foreach ( $col as $val ) {
								$val = explode ( ':', $val );
								$model->id = $val [0];
								$model->sort = $val [1];
								$result = $model->save ();
								if (! $result) {
										break;
								}
						}
						//提交事务
						$model->commit ();
						if ($result!==false) {
								//采用普通方式跳转刷新页面
								$this->success ( '更新成功' );
						} else {
								$this->error ( $model->getError () );
						}
				}
		}
		
	public function getHouse(){
				$hotel_id = intval($_POST['hotel_id']);
				$data = M('House')->where('hotel_id ='.$hotel_id.' and status =1')->findAll();
				$str = '<option value="0">--所有房型--</option>';
				foreach ($data as $value) {
						$str .= '<option value="'.$value['id'].'">'.$value['name'].'</option>';
				}
				echo $str;
		}

		/**
		 * 返回多个房间，checkbox
		 */
		public function getRoom(){
				$house_id = intval($_POST['house_id']);
				//$data = M('Room')->where('house_id ='.$house_id.' and status=1')->order('sort asc')->findAll();
				//查找当天可用房间
				$data = getAvailableRooms($house_id, '');
				$str = '';
				if(!data){
						return $str= "<span id='room'>没有房间</span>";
				}
				$str = " <span id='room'> 房间： ";
				foreach ($data as $value) {
						$str .= '<input type="checkbox" name="room_id[]" id="room_id" value="'.$value['room_id'].'">'.$value['room_no'];
				}
				echo $str.="</span>";
		}

		/**
		 * 返回多个房间，radio
		 */
		public function getRoom2(){
				$house_id = intval($_POST['house_id']);
				if($_REQUEST['nocheck'] == 1){
						$data = M('Room')->where('house_id ='.$house_id.' and status=1' )->order('sort asc')->findAll();
				}else{
						 //查找当天可用房间 .默认需要检查房间的当前可用时间
						$data = getAvailableRooms($house_id, '');
				}
				$str = '';
				if(!data){
						echo $str= "<input type='radio' id='room_id' value=0 name='room_id'>没有房间";
				}
				foreach ($data as $value) {
						//检查房间可用时，房间编号 是 room_id，不是id，注意区别
						$room_id = $_REQUEST['nocheck'] == 1 ? ( $value['id'] ):( $value['room_id'] );
						$str .= '<input type="radio" name="room_id" id="room_id" value="'.$room_id.'">'.$value['room_no'];
				}
				echo $str;
		}

		/**
		 * 计算租房的总价格，注意酒店一天以本日中午12：00到次日中午12：00为一天[暂不管]
		 * @param <type> $house_id 房型ID(暂只支持单个房型)TODO
		 * @param <type> $amount （预订相应房型的房间数量）
		 * @param <type> $start_time 入住时间
		 * @param <type> $end_time  离开时间
		 */
		public function calPrice(){
				$start_time = strtotime($_POST['start_time']);
				$end_time = strtotime( $_POST['end_time'] );
				$amount = intval( $_POST['amount'] );
				$house_id = intval( $_POST['house_id'] );
				//停留时间
				$stayDay = ceil ( ($end_time - $start_time)/(60*60*24) );//向下取一位
				//$end_hour = date('h',$end_time);
				$realPrice = $this->getRealPrice($house_id, $stayDay);
				$totalPrice = $realPrice*$stayDay*$amount;
		
				echo $totalPrice;
				//echo array($realPrice,$stayDay,$totalPrice);
		}

		/**
		 *根据入住停留时间获取每天的房价
		 * @param <type> $house_id 房型
		 * @param <type> $stayDay 租房的天数
		 * @return <type>
		 */
		public function getRealPrice($house_id,$stayDay){
				$house_id = intval($house_id);
				$stayDay = intval($stayDay);
				$cond = array();
				if($stayDay > 0){
						$cond['start_day'] = array('elt',$stayDay);
						$cond['end_day'] = array('egt',$stayDay);
						$cond['house_id'] = $house_id;
						$price = M('Price')->where($cond)->order('start_day asc')->find();
						if(is_null($price)){
								unset($cond['end_day']);
								$cond['start_day'] = $cond['end_day'] = 0 ;
								$price = M('Price')->where($cond)->order('start_day asc')->find();//default price
						}
						$realPrice = $price['price'];
						return $realPrice;
				}
		}

		/**
		 *处理上传图片，包括公寓及房型，文章等的图片（文章图片暂不做）
		 * @param <type> $objId 公寓或房型ID
		 * @param <type> $type type=0 公寓，1房型,2 form文章或广告
		 * @return <type>
		 */
		public function process_photo($objId,$type=0) {
				//$_FILES = $files;
			switch ($type) {
				case '0':
					$object = 'hotel';
					break;
				case '1':
					$object = 'house';
					break;
				case '2':
					$object = 'form';
					break;
				default:
					$object = 'hotel';
					break;
			}
             //新上传图片的排序,如果为空，还要过滤掉空值,默认新图片的排序位必须存在，否则易错位。
             $pic_sorts = $_POST['pic_sort'];
             //已经上传图片的排序
             $old_sorts = $_POST['old_sort'];
             $new_sorts = array();
             $i = 0;
             foreach($pic_sorts as $ks=>$kvalue ){
                if(!empty($kvalue) ){
                    $new_sorts[$i] = $kvalue;
                    $i ++;
                }
             }

             
            import("@.ORG.UploadFile");
                //如果指定类型则删除原有的上传图片
			 $cond=empty($_FILES['logo']['name'])?'':'attachfunc=2'; //如果定义了上传logo则删除原有的logo
			 $old_attach = implode(',',$_POST['old_attach']);
			 if (!empty($old_attach)) {
					 $cond.=" or (attachfunc=1 and id not in ({$old_attach}))";
			 }else {
					 $cond.=" or attachfunc=1";
			 }
			 $cond = (substr($cond,0,4)==' or ')?substr($cond,4):$cond;
			 $cond = $object."_id=".$objId." and (".$cond.")";
			 $data = M('Attach')->where($cond)->select();
			 //删除指定的文件
			 if ($data) {
					 foreach ($data as $key => $val) {
							 unlink($val['path'].'thumb_'.$val['filename']);
							 unlink($val['path'].$val['filename']);
					 }
					 M('Attach')->where($cond)->delete();
			 }
             //排序原图片
             foreach($old_sorts as $osk=> $svalue){
                 M('Attach')->where('attachfunc=1 and id='.$_POST['old_attach'][$osk])->setField('sort',$svalue);
             }

				$upload = new UploadFile();
				$savePath = './Public/Uploads/'.$object.'/';
				if(!file_exists($savePath)) {
						mkdir($savePath,0777,true);
				}
				$upload->savePath =  $savePath;
				$upload->saveRule =  'uniqid';
				//$upload->saveRule =  '';//为空保持文件名不变，SEO友好或将来把产品名写入图片名称中TODO savename需要改为name+uninquId
				$upload->thumb   =  true;
				$upload->thumbMaxWidth = 100;
				$upload->thumbMaxHeight = 100;
				$upload->thumbPrefix = 'thumb_';
				if (!$upload->upload()) {
						$errormsg = $upload->getErrorMsg();
						if ($errormsg!='没有选择上传文件') {
								$this->errmsg .= "<br/>";
								$this->errmsg .=  $upload->getErrorMsg();//添加出错信息
						}
						return false;
				}
				$file_info = $upload->getUploadFileInfo();
				$islogo = empty($_FILES['logo']['name'])?0:1;
				//import("@.ORG.Image");
                $ps = 0; //新图片 索引值
				foreach ($file_info as $key => $value) {
						//Image::water($savePath.$value['savename'], './Public/Images/home/ok_water.png');//透明度80% 水印功能暂不做
						$data = array(
										$object.'_id'=>$objId,
										'filename'=>$value['savename'],
										'attachfunc'=>1,
										'path'=>$value['savepath'],
										'url'=>$value['savepath'].$value['savename'],
										'size'=>intval($value['size']/1024),
										'attachext'=>$value['extension'],
										'create_time'=>time(),
										'status'=>1,
                                        'sort' => $new_sorts[$ps]
						);
						if ($key==0 && $islogo==1) {
								$data['attachfunc']=2;
                                $ps = -1; //让新图片 排序略过Logo
						}
                        $ps++;
						$insid = M('Attach')->add($data);
				}
		}

		public function success($message,$ajax=false,$waitSecond = 0.1){
				$this->assign('waitSecond',$waitSecond);
				parent::success($message, $ajax);

		}
		/**type=0预订单，1为入住单
		 *生成单号如 20110528-001 ，前几位为当前单子的日期，后三位自动增长
		 */
		public function genManNo($type=0){
				$currday = date('Ymd');
				$model = '';
				if($type == 0) { //生成预订单号YD20110530-001
						$model = M('Order');
						$lastNo = $model ->order('id desc')->field('order_no')->find();
						$value = explode('-',$lastNo['order_no'] );
						if(empty($value)){
							 return $no = 'YD'.$currday.'-001';
						}
						else{
								if( substr($value['0'],2) == $currday){
										$value['1'] += 1;
										 $value['1'] = sprintf("%03d", $value['1'] ); //格式化为001
								}
								else{
										$value['1'] = '001';
								}
								return $no = 'YD'.$currday.'-'.$value['1'];
						}
				}
				elseif($type == 1) {  //生成入住单号 20110528-001
						$model = M('Checkin');
						$lastNo = $model ->order('id desc')->field('checkin_no')->find();
						$value = explode('-',$lastNo['checkin_no'] );
						if(empty($value)){
							 return $no = $currday.'-001';
						}
						else{
								if($value['0'] == $currday){
										$value['1'] += 1;
										 $value['1'] = sprintf("%03d", $value['1'] ); //格式化为001
								}
								else{
										$value['1'] = '001';
								}
								return $no = $currday.'-'.$value['1'];
						}
				}
		}

		public function getAllMember() {
				$q = strtolower($_GET["term"]);
				if (!$q) return;
				$data = M('Member')->where('status = 1')->field('id,account,name')->order("create_time desc")->findAll();
				$allresult = array();
				foreach($data as $key=>$value) {
						$allresult[ $value['id'] ] = $value['account'].'('.$value['name'].')';
				}
				$result = array();
				foreach ($allresult as $value=>$key) {
						if (strpos(strtolower($key), $q) !== false) {
								array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key)));
						}
						if (count($result) > 11)
								break;
				}
				echo array_to_json($result);
				//$this->ajaxReturn($result,'',1);
		}

		 public function getHotelTree(){
				getHotelTreeJson();
		}

		//获得县市
		public function getCountry()
		{
				$city_code = intval($_POST["city_code"]);
				$str = "";
				foreach(M("Country")->where("city_code={$city_code}")->select() as $value){
						$str .= "<option value='{$value[coun_code]}'>{$value['coun_name']}</option>";
				}
				echo $str;
		}
		public function getCity()
		{
				$province_code = intval($_POST["prov_code"]);
				$str = "";
				foreach(M("City")->where("prov_code={$province_code}")->select() as $value){
						$str .= "<option value='{$value[city_code]}'>{$value['city_name']}</option>";
				}
				echo $str;
		}

		//获取最新的交易统计数据，ajax返回
		public function getLatestData(){
				$curday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
				 $curday_night = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
				 $msgmap = array(
						 'approved' => 1, //后台未回复
						 'status' => 0, //默认禁用状态
						 'parent' => 0, //只列出前台客户的发言
						 'user_id' => 0, //只列出前台客户的发言
				 );
				 $Comment = M('Comment');
				 $Order = M('Order');
				 $Checkin = M('Checkin');
				 $Member = M('Member');
				 $Landlord = M('Landlord');
				 $Clean = M('Room_maintain');
				 $count_msgs =$Comment ->where($msgmap)->count();
				 $count_order = $Order->where('status = 1')->count();//状态为待确认的所有订单
				 $count_checkin = $Checkin->where('start_time >='.$curday)->count();//统计今日入住的客户，以今日入住时间为准
				 $count_live_checkin = A('Housestats')->countTodayCheckinRooms();//统计入住中的入住单
				 $count_member = $Member->where('create_time >='.$curday." and type = 0")->count();//如果是今天且会员类型未被修改为其他类型的，则视为新会员
				 $count_lesspay = $Checkin->where('status =2')->count();//余款未付

					$landlord_map = array(
						 'alert_time' => array('between','1,'.time()),
				 );
					$count_landlord = $Landlord->where($landlord_map)->count();//今日交租房东管理
					
				 $leave_map = array(
						 'alert_time' => array('between','1,'.time()),
				 );
				 $count_house = $Checkin->where($leave_map)->count();//按到期时间进行提醒，>=即提醒，止到用户删除或修改了这个提醒 时间

				 $clean_map = array(//打扫提醒时间
						 'alert_time' => array('between','1,'.time()),
						 'type' =>0,//打扫的
				 );
				 $count_clean = $Clean->where($leave_map)->count();//按到期时间进行提醒，>=即提醒，止到用户删除或修改了这个提醒 时间
				 
				 $process_order_map = array(
						 'status'=> array('between','2,4'),
						 );//处理中的订单
				$count_process_order = $Order->where($process_order_map)->count();
				$count_todo = M('Todo')->where('alert_time !=0 and user_id='.$_SESSION[C('USER_AUTH_KEY')])->count();
				$sumRentCost = (int)sumRentCost('', '', '', '',date('Y'), date('m'));
				$alert_value = M('Configure')->where('var_name = "alert_type" ')->getField('value');
				$count_today_free_rooms = count(getTodayFreeRooms());
			 $count_to_check = $Checkin->where('status = 4')->count();//退款待结帐

				$data = array(
						'count_process_order' => $count_process_order,//处理中的订单
						'count_msgs' => $count_msgs,
						'count_order' => $count_order,
					 'count_checkin'=>$count_checkin,
						'count_member'=>$count_member,
						'count_house'=>$count_house,
						'count_lesspay'=>$count_lesspay,
						'count_landlord'=>$count_landlord,
						'count_live_checkin'=>$count_live_checkin,
						'count_clean'=>$count_clean,
						'count_todo' => $count_todo,
						'sumRentCost' => $sumRentCost,
						'alert_value' => $alert_value,
						'count_today_free_rooms' => $count_today_free_rooms,
						'count_to_check' => $count_to_check,
						);

				$this->ajaxReturn($data,'',1);
		}

		//获取最新的订单信息，ajax return
		public function getOrders(){
				$orders = M('Order') ->where('status = 1')->findAll();
				$tr = '<tr class="row">
								<th>编号</th><th>会员名</th><th>房间</th><th>房型</th><th>入住时间</th><th>离开时间</th><th>总金额</th><th>下单时间</th>
								<th>状态</th><th>操作</th></tr>';
				foreach ($orders as $key => $value) {
						$tr .= ' <tr class="out">';
						$tr .= '<td>'.$value['id'] . '</td>';
						$tr .= '<td>'.getMemberInfo($value['member_id']) . '</td>';
						$tr .= '<td>'.getRoomNo($value['room_id']) . '</td>';
						$tr .= '<td>'.getModelName($value['house_id'],'House') . '</td>';
						$tr .= '<td>'.toDate($value['start_time']) . '</td>';
						$tr .= '<td>'.toDate($value['end_time']) . '</td>';
						$tr .= '<td>'.$value['totalprice'] . '</td>';
						$tr .= '<td>'.toDate($value['create_time']) . '</td>';
						$tr .= '<td>'.getConfigVal($value['status'],'orderStatus') . '</td>';
						$tr .= '<td><a href="'.__APP__.'/Order/edit/id/'.$value['id'].'/return/home">详情</a></td>';
						$tr .= '</tr>';

				}
				$this->ajaxReturn($tr,'',1);
		}
	 
	 //获取当天最新客户，并ajax返回
	 public function getNewMembers(){
				$curday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
				$members = M('Member')->where('create_time >='.$curday." and type = 0")->findAll();
				$tr = '<tr class="row">
								<th>编号</th><th>用户名</th><th>姓名</th><th>性别</th><th>手机</th><th>邮箱</th><th>注册时间</th><th>类型</th><th>状态</th><th>操作</th></tr>';
				foreach ($members as $key => $value) {
						$tr .= ' <tr class="out">';
						$tr .= '<td>'.$value['id'] . '</td>';
						$tr .= '<td>'.$value['account']. '</td>';
						$tr .= '<td>'.$value['name'] . '</td>';
						$tr .= '<td>'.getSex($value['sex']). '</td>';
						$tr .= '<td>'.$value['mobile']. '</td>';
						$tr .= '<td>'.$value['email'] . '</td>';
						$tr .= '<td>'.toDate($value['create_time']) . '</td>';
						$tr .= '<td>'.getConfigVal($value['type'],'customer_type') . '</td>';
						$tr .= '<td>'.getStatus($value['status']) . '</td>';
						$tr .= '<td><a href="'.__APP__.'/Member/edit/id/'.$value['id'].'/return/home">详情</a></td>';
						$tr .= '</tr>';

				}
				$this->ajaxReturn($tr,'',1);
		}

		//获取当天最新留言，并ajax返回
	 public function getNewMsg(){
				$msgmap = array(
						 'approved' => 1, //后台未回复
						 'status' => 0, //默认禁用状态
						 'parent' => 0, //只列出前台客户的发言
						 'user_id' => 0, //只列出前台客户的发言
				 );
				 $Comment = M('Comment');
				$comments = $Comment->where($msgmap)->findAll();
				$tr = '<tr class="row">
								<th>编号</th><th>留言</th><th>会员</th><th>咨询对象</th><th>咨询时间</th><th>状态</th><th>操作</th></tr>';
				foreach ($comments as $key => $value) {
						$tr .= ' <tr class="out">';
						$tr .= '<td>'.$value['id'] . '</td>';
						$tr .= '<td>'.cutstr($value['content'],40). '</td>';
						$tr .= '<td>'.getMemberInfo($value['member_id'] ). '</td>';
						$tr .= '<td>'.getPName($value['pid'],$value['type']). '</td>';
						 $tr .= '<td>'.toDate($value['create_time']) . '</td>';
					 
						$tr .= '<td>'.getConfigVal($value['approved'],'comStatus') . '</td>';
						$tr .= '<td><a href="'.__APP__.'/Comment/edit/id/'.$value['id'].'/return/home">详情</a></td>';
						$tr .= '</tr>';

				}
				$this->ajaxReturn($tr,'',1);
		}

		//获取处理中订单信息，ajax return
		public function getProcessOrders(){
				$process_order_map = array(
						 'status'=> array('between','2,4'),
						 );//处理中的订单
				$orders = M('Order') ->where($process_order_map)->findAll();
				$tr = '<tr class="row">
								<th>编号</th><th>会员名</th><th>房间</th><th>房型</th><th>入住时间</th><th>离开时间</th><th>总金额</th><th>下单时间</th>
								<th>状态</th><th>操作</th></tr>';
				foreach ($orders as $key => $value) {
						$tr .= ' <tr class="out">';
						$tr .= '<td>'.$value['id'] . '</td>';
						$tr .= '<td>'.getMemberInfo($value['member_id']) . '</td>';
						$tr .= '<td>'.getRoomNo($value['room_id']) . '</td>';
						$tr .= '<td>'.getModelName($value['house_id'],'House') . '</td>';
						$tr .= '<td>'.toDate($value['start_time']) . '</td>';
						$tr .= '<td>'.toDate($value['end_time']) . '</td>';
						$tr .= '<td>'.$value['totalprice'] . '</td>';
						$tr .= '<td>'.toDate($value['create_time']) . '</td>';
						$tr .= '<td>'.getConfigVal($value['status'],'orderStatus') . '</td>';
						$tr .= '<td><a href="'.__APP__.'/Order/edit/id/'.$value['id'].'/return/home">详情</a></td>';
						$tr .= '</tr>';

				}
				$this->ajaxReturn($tr,'',1);
		}

		 //获取到期客户，并ajax返回
	 public function getHouses(){
				$leave_map = array(
						 'alert_time' => array('between','1,'.time()),
				 );
				 $Comment = M('Checkin');
				$comments = $Comment->where($leave_map)->findAll();
				$tr = '<tr class="row">
								<th>编号</th><th>入住单号</th><th>订单编号</th><th>会员名</th><th>房间</th><th>入住时间</th><th>离开时间</th><th>结账金额</th><th>创建时间</th>
								<th>状态</th><th>操作</th></tr>';
				foreach ($comments as $key => $value) {
						$tr .= ' <tr class="out">';
						$tr .= '<td>'.$value['id'] . '</td>';
						$tr .= '<td>'.$value['checkin_no']. '</td>';
						$tr .= '<td>'.$value['order_id']. '</td>';
						$tr .= '<td>'.$value['member_name']. '</td>';
						$tr .= '<td>'.getRoomNo($value['room_id']). '</td>';
						$tr .= '<td>'.toDate($value['start_time']) . '</td>';
						$tr .= '<td>'.toDate($value['end_time']) . '</td>';
						$tr .= '<td>'.$value['balanceprice']. '</td>';
						$tr .= '<td>'.toDate($value['create_time']) . '</td>';
					 
						$tr .= '<td>'.getConfigVal($value['status'],'checkinstatus') . '</td>';
						$tr .= '<td><a href="'.__APP__.'/Checkin/edit/id/'.$value['id'].'/return/home">详情</a></td>';
						$tr .= '</tr>';

				}
				$this->ajaxReturn($tr,'',1);
		}
	 
			//获取欠款客户，并ajax返回
	 public function getLessPay(){
				 $Comment = M('Checkin');
				$comments = $Comment->where('status =2')->findAll();
				$tr = '<tr class="row">
								<th>编号</th><th>入住单号</th><th>订单编号</th><th>会员名</th><th>房间</th><th>入住时间</th><th>离开时间</th><th>结账金额</th><th>创建时间</th>
								<th>状态</th><th>操作</th></tr>';
				foreach ($comments as $key => $value) {
						$tr .= ' <tr class="out">';
						$tr .= '<td>'.$value['id'] . '</td>';
						$tr .= '<td>'.$value['checkin_no']. '</td>';
						$tr .= '<td>'.$value['order_id']. '</td>';
						$tr .= '<td>'.$value['member_name']. '</td>';
						$tr .= '<td>'.getRoomNo($value['room_id']). '</td>';
						$tr .= '<td>'.toDate($value['start_time']) . '</td>';
						$tr .= '<td>'.toDate($value['end_time']) . '</td>';
						$tr .= '<td>'.$value['balanceprice']. '</td>';
						$tr .= '<td>'.toDate($value['create_time']) . '</td>';
					 
						$tr .= '<td>'.getConfigVal($value['status'],'checkinstatus') . '</td>';
						$tr .= '<td><a href="'.__APP__.'/Checkin/edit/id/'.$value['id'].'/return/home">详情</a></td>';
						$tr .= '</tr>';

				}
				$this->ajaxReturn($tr,'',1);
		}

		/**返回待结账客户
		**/

		public function getToCheck(){
				 $Comment = M('Checkin');
				$comments = $Comment->where('status =4')->findAll();
				$tr = '<tr class="row">
								<th>编号</th><th>入住单号</th><th>订单编号</th><th>会员名</th><th>房间</th><th>入住时间</th><th>离开时间</th><th>结账金额</th><th>创建时间</th>
								<th>状态</th><th>操作</th></tr>';
				foreach ($comments as $key => $value) {
						$tr .= ' <tr class="out">';
						$tr .= '<td>'.$value['id'] . '</td>';
						$tr .= '<td>'.$value['checkin_no']. '</td>';
						$tr .= '<td>'.$value['order_id']. '</td>';
						$tr .= '<td>'.$value['member_name']. '</td>';
						$tr .= '<td>'.getRoomNo($value['room_id']). '</td>';
						$tr .= '<td>'.toDate($value['start_time']) . '</td>';
						$tr .= '<td>'.toDate($value['end_time']) . '</td>';
						$tr .= '<td>'.$value['balanceprice']. '</td>';
						$tr .= '<td>'.toDate($value['create_time']) . '</td>';
					 
						$tr .= '<td>'.getConfigVal($value['status'],'checkinstatus') . '</td>';
						$tr .= '<td><a href="'.__APP__.'/Checkin/edit/id/'.$value['id'].'/return/home">详情</a></td>';
						$tr .= '</tr>';

				}
				$this->ajaxReturn($tr,'',1);
		}

			//获取今日入住客户，并ajax返回
	 public function getCheckins(){
				$curday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
				 $Comment = M('Checkin');
				$comments = $Comment->where('start_time >='.$curday)->findAll();
				$tr = '<tr class="row">
								<th>编号</th><th>入住单号</th><th>订单编号</th><th>会员名</th><th>房间</th><th>入住时间</th><th>离开时间</th><th>结账金额</th><th>创建时间</th>
								<th>状态</th><th>操作</th></tr>';
				foreach ($comments as $key => $value) {
						$tr .= ' <tr class="out">';
						$tr .= '<td>'.$value['id'] . '</td>';
						$tr .= '<td>'.$value['checkin_no']. '</td>';
						$tr .= '<td>'.$value['order_id']. '</td>';
						$tr .= '<td>'.$value['member_name']. '</td>';
						$tr .= '<td>'.getRoomNo($value['room_id']). '</td>';
						$tr .= '<td>'.toDate($value['start_time']) . '</td>';
						$tr .= '<td>'.toDate($value['end_time']) . '</td>';
						$tr .= '<td>'.$value['balanceprice']. '</td>';
						$tr .= '<td>'.toDate($value['create_time']) . '</td>';
					 
						$tr .= '<td>'.getConfigVal($value['status'],'checkinstatus') . '</td>';
						$tr .= '<td><a href="'.__APP__.'/Checkin/edit/id/'.$value['id'].'/return/home">详情</a></td>';
						$tr .= '</tr>';

				}
				$this->ajaxReturn($tr,'',1);
		}

		//return to clean houses with ajax
		public function getCleans(){
				$clean_map = array(//打扫提醒时间
						 'alert_time' => array('between','1,'.time()),
						 'type' =>0,//打扫的
				 );
				$Clean = M('Room_maintain');
				$comments = $Clean->where($clean_map)->findAll();
				$tr = '<tr class="row">
							 <th>编号</th><th>房间</th><th>起始时间</th><th>截止时间</th><th>操作</th></tr>';
				foreach ($comments as $key => $value) {
						$tr .= ' <tr class="out">';
						$tr .= '<td>'.$value['id'] . '</td>';
						$tr .= '<td>'.getRoomBh($value['room_id']). '</td>';
						$tr .= '<td>'.toDate($value['start_time']) . '</td>';
						$tr .= '<td>'.toDate($value['end_time']) . '</td>';
						$tr .= '<td><a href="'.__APP__.'/Room_maintain/edit/id/'.$value['id'].'/return/home">详情</a></td>';
						$tr .= '</tr>';
				}
				$this->ajaxReturn($tr,'',1);
		}

		//return to landords houses with ajax
		public function getLandords(){
				$landlord_map = array(
						 'alert_time' => array('between','1,'.time()),
				 );
				$Clean = M('Landlord');
				$comments = $Clean->where($landlord_map)->findAll();
				$tr = '<tr class="row">
							 <th>编号</th><th>房间</th><th>租金</th><th>交租时间</th><th>操作</th></tr>';
				foreach ($comments as $key => $value) {
						$tr .= ' <tr class="out">';
						$tr .= '<td>'.$value['id'] . '</td>';
						$tr .= '<td>'.getRoomBh($value['room_id']). '</td>';
						 $tr .= '<td>'.$value['money'] . '</td>';
						$tr .= '<td>'.toDate($value['pay_time']) . '</td>';
						$tr .= '<td><a href="'.__APP__.'/Landlord/edit/id/'.$value['id'].'/return/home">详情</a></td>';
						$tr .= '</tr>';
				}
				$this->ajaxReturn($tr,'',1);
		}

		//return todo with ajax
		public function getTodos(){
				$comments = M('Todo')->where('alert_time !=0 and user_id='.$_SESSION[C('USER_AUTH_KEY')])->findAll();
				$tr = '<tr class="row">
							 <th>编号</th><th>计划</th><th>地址</th><th>开始时间</th><th>结束时间</th><th>状态</th><th>操作</th></tr>';
				foreach ($comments as $key => $value) {
						$tr .= ' <tr class="out">';
						$tr .= '<td>'.$value['id'] . '</td>';
						$tr .= '<td>'.$value['subject']. '</td>';
						 $tr .= '<td>'.$value['address'] . '</td>';
						$tr .= '<td>'.toDate($value['start_time']) . '</td>';
						$tr .= '<td>'.toDate($value['end_time']) . '</td>';
						$tr .= '<td>'.getConfigVal($value['status'],'todostatus') . '</td>';
						$tr .= '<td><a href="'.__APP__.'/Todo/edit/id/'.$value['id'].'/return/home">详情</a></td>';
						$tr .= '</tr>';
				}
				$this->ajaxReturn($tr,'',1);
		}

}
?>
